/*
	Authors: Andy Wu, Faiz-ur Rahman, Samuel Thacker
	Description: Main file for program.
	Revisions:
		2012/2/07 - Creation of this program file.
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "FileReader.h"

#include "disassembler.h"
#include "DecodedStructs.h"

#include "format.h"

void PrintUsage();

int main(int argc, char *argv[])
{
	int x = 0;
	char *input = NULL, *output = NULL;

	PrintUsage();
	
/*entering while loop to check options entered*/
    while(x < argc)
	{
		/* input loop */
		if(0 == strcmp(&argv[x][0], "-i")) 
		{
			if(x < argc - 1)
			{	
				input = (char *)malloc(sizeof(char) * (strlen(&argv[x + 1][0]) + 1));
				strcpy(input, argv[x + 1]);
			}
			else
			{
				printf("Missing argument for input name!\n");
				free(input);
				free(output);
				return 5;
			}
	
			/* Moves onto next element in command */
			x += 2;
		}
		
		/* output loop */
		if(0 == strcmp(&argv[x][0], "-o"))
		{
			if(x < argc - 1)
			{	
				output = (char *)malloc(sizeof(char) * (strlen(&argv[x + 1][0]) + 1));
				strcpy(output, argv[x + 1]);
			}
			else
			{
				printf("Missing argument for output name!\n");
				free(input);
				free(output);
				return 5;
			}
			
			/* Moves onto next element in command */
			x += 2;
		}
		
		/* Moves onto next element in command */
		x++;
	}

	if(!input){
		printf("Missing argument for input name!\n");
		free(input);
		free(output);
		return 5;
	}

	if(!output){
		printf("Missing argument for output name!\n");
		free(input);
		free(output);
		return 5;
	}
	


	/*filereaderpart*/
	ILIST *list;
	int length;	/*initializing variable to store length of input*/
	char *extension=malloc(100*sizeof(char));
	length = strlen(input);
	strcat(extension,&input[length-3]);
	char *outfr=malloc(100*sizeof(char));
	strncpy(outfr,input,length-4);

	if(strncmp(extension,"hex",3)==0)
		{
		convertHex(outfr);
		list= ReadBinFileIvanStyleInt(strcat(outfr,".bin"));
		}
	else if(strncmp(extension,"elf",3)==0)
		{
	    	convertelf(outfr);
		list= ReadBinFileIvanStyleInt(strcat(outfr,".bin"));
		}
	else if(strncmp(extension,"bin",3)==0)
		{
		list= ReadBinFileIvanStyleInt(input);
		}
	else
		{
		perror("Invalid input");
		}
	
	/*disassemblerpart*/
	disassembler(list);


	/*fileformatpart*/
	char *fname2=strcat(output,".asm");
	format(list,fname2);
	DeleteInstructionList(list);

	printf("input = %s and output = %s\n", input, output);

	free(input);
	free(output);
	return 0;
}

void PrintUsage()
	{
	printf("\nFormat on command line is:\n"
	"Disassemble -i input_file_name -o output_file_name\n"
	"-i\t\tto provide the input file name (with file extension)\n"
	"-o\t\tto provide the  output file name (without file extension)\n");
	}
